package com.xu.cloud.common.template;

import com.xu.cloud.common.pojo.http.req.BaseRequest;
import com.xu.cloud.common.pojo.http.resp.BaseResponse;
import com.xu.cloud.common.process.IProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 模板方法抽象类
 *
 * @author xuguan
 * @since 2023/4/3
 */
public abstract class AbstractRequestTemplate<Req extends BaseRequest, Resp extends BaseResponse>
        implements RequestTemplate<Req, Resp>, IProcessor<Req, Resp> {
    protected static final Logger log = LoggerFactory.getLogger(AbstractRequestTxTemplate.class);

    @Override
    public Resp process(Req req) {
        Resp resp = null;
        Exception ex = null;
        try {
            this.recv(req);
            this.valid(req);
            this.check(req);
            this.preRequest(req);
            log.info(">>>>>>>>>>> request start");
            resp = this.request(req);
            log.info(">>>>>>>>>>> request end");
            return resp;
        } catch (Exception exception) {
            log.info(">>>>>>>>>>> request fail");
            ex = exception;
            throw exception;
        } finally {
            try {
                postRequest(req, resp, ex);
            } catch (Exception exception) {
                log.info(">>>>>>>>>>> postRequest fail, not throw exception");
            }
        }
    }
}
